package com.fourth.service.impl;


import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayOpenPublicTemplateMessageIndustryModifyRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.fourth.config.AlipayConfiguration;
import com.fourth.service.UbAliPayService;
import com.fourth.service.UbOrderService;
import com.fourth.util.PayUtil;
import com.fourth.vo.PayInfoVO;
import com.ljx.entity.Order;
import com.ljx.vo.Result;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Mr.ma
 * @since 2023/3/3 14:22
 **/
@Service
public class UbAliPayServiceImpl implements UbAliPayService {

    @Resource
    private AlipayConfiguration alipayConfiguration;

    @Resource
    private PayUtil payUtil;


    @Override
    public String webPagePay(String outTradeNo, String subjectName, BigDecimal totalAmount) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfiguration.getServerUrl(),
                alipayConfiguration.getAppId(),
                alipayConfiguration.getPrivateKey(),
                alipayConfiguration.getFormat(),
                alipayConfiguration.getCharset(),
                alipayConfiguration.getAlipayPublicKey(),
                alipayConfiguration.getSignType());

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(alipayConfiguration.getNotify_url());
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(alipayConfiguration.getReturn_url());

        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", outTradeNo);
        //支付金额，最小值0.01元
        bizContent.put("total_amount", totalAmount);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", subjectName);
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        String result = alipayClient.pageExecute(request).getBody();

        return result;
    }

    @Override
    public String returnUrl(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(), alipayConfiguration.getCharset(), "RSA2");

        //验证成功
        if (verify_result) {
            //请在这里加上商户的业务逻辑程序代码
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                payUtil.paySuccess(out_trade_no,1);
                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            return "通知成功";

            //
        } else {//验证失败

            return "通知失败";
        }
    }

    @Override
    public String notifyUrl(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(), alipayConfiguration.getCharset(), "RSA2");
        if(verify_result){
            //验证成功
            return "调用成功";
        }else{
            return "调用失败";
        }
    }


    @Override
    public PayInfoVO f2fPay(String outTradeNo, String subjectName, BigDecimal totalAmount) {

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfiguration.getServerUrl(),
                alipayConfiguration.getAppId(),
                alipayConfiguration.getPrivateKey(),
                alipayConfiguration.getFormat(),
                alipayConfiguration.getCharset(),
                alipayConfiguration.getAlipayPublicKey(),
                alipayConfiguration.getSignType());

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(alipayConfiguration.getNotify_url());
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(alipayConfiguration.getReturn_url());
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", outTradeNo);
        //支付金额，最小值0.01元
        bizContent.put("total_amount", totalAmount);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", subjectName);


        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (response != null && response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        PayInfoVO payInfoVO = new PayInfoVO();
        payInfoVO.setPrice(totalAmount.toString());
        payInfoVO.setOrderNo(outTradeNo);
        payInfoVO.setCodeUrl(response.getQrCode());
        return payInfoVO;
    }


    @Override
    public Result queryPayStatus(String code) {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfiguration.getServerUrl(),
                alipayConfiguration.getAppId(),
                alipayConfiguration.getPrivateKey(),
                alipayConfiguration.getFormat(),
                alipayConfiguration.getCharset(),
                alipayConfiguration.getAlipayPublicKey(),
                alipayConfiguration.getSignType());

        //创建查询API对应的request类
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();


        //设置业务参数
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", code);
        request.setBizContent(bizContent.toString());

        //通过alipayClient调用API，获得对应的response类
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
            if (response.getTradeStatus().equals("TRADE_SUCCESS")) {
                return payUtil.paySuccess(code,1);
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return new Result(5000, "订单未支付");
    }

    @Override
    public void addRedis(String code, String value) {
        payUtil.addRedis(code,value);
    }

    @Override
    public String getRedis(String code) {
        return payUtil.getRedis(code);
    }

    @Override
    public Result changeStock(String goodsid, Integer num) {
       return payUtil.changeStock(goodsid, num);
    }
}
